package controllers

import (
	"fmt"
	"myblog/utils"
	"time"

	beego "github.com/beego/beego/v2/server/web"
)

type EditController struct {
	beego.Controller
}

type editmd struct {
	Title   string `form:"Title"`
	Content string `form:"Content"`
}

func (this *EditController) Get() {
	postdir, _ := beego.AppConfig.String("postdir")
	flash := beego.ReadFromRequest(&this.Controller)
	err := flash.Data["error"]
	err = flash.Data["notice"]
	if len(err) != 0 {
		fmt.Println(err)
	}
	file := this.Ctx.Input.Param(":splat")
	if file == "" {
		//获取时间日期
		tim := time.Now()
		tim.Unix()
		ti := tim.Format("2006-01-02")

		content := "title:" + "My First Post\n" + "date:" + ti + " " + "作者：" + "\n" + "#标题" + "\n"
		this.Data["Title"] = postdir + "test.md"
		this.Data["Content"] = content
	} else {
		content := utils.ReadFile("/" + file)
		this.Data["Title"] = "/" + file
		this.Data["Content"] = content
	}

	this.TplName = "model/editmd.tpl"
	this.LayoutSections = make(map[string]string)
	this.LayoutSections["IndexHead"] = "model/ahead.tpl"
	this.LayoutSections["IndexNavbar"] = "model/navbar.tpl"
	this.LayoutSections["IndexNav"] = "model/nav.tpl"
	this.LayoutSections["IndexFoot"] = "model/afoot.tpl"
	this.Layout = "index.tpl"
}

func (this *EditController) Post() {
	// useremail := this.GetSession("name").(string)
	editmd := editmd{}
	// 初始化flash
	flash := beego.NewFlash()
	this.ParseForm(&editmd)

	err := utils.SaveToFile(editmd.Title, editmd.Content)
	if err == nil {
		flash.Error("提交成功。")
		this.Redirect("/admin/table", 302)
	} else {
		flash.Error("标题重复。")
		flash.Notice(editmd.Content)
		this.Redirect("/admin/edit", 302)
	}
	flash.Store(&this.Controller)
}
